import pickle
import base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user,response):
    """
    合并cookie和redis的购物车数据
    # 1 获取cookie数据
    # 2 如果存在
          # 获取redis中的数据
          # 遍历cookie
          # 保存到redis
          # 删除cookie
    # 3 不存在直接返回响应,不处理
    """
    cookie_str = request.COOKIES.get('cart')

    if cookie_str is not None:
        cookie_cart = pickle.loads(base64.b64decode(cookie_str.encode()))

        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        # 将id和count转化为int类型
        cart = {}
        for sku_id, count in redis_cart.items():
            cart[int(id)] = int(count)

        selected_sku_id_list = []
        for sku_id, selected_count_dict in cookie_cart.items():
            # 如果有覆盖，没有添加
            cart[sku_id] = selected_count_dict['count']

            # 处理勾选状态
            if selected_count_dict['selected']:
                selected_sku_id_list.append(sku_id)

        # 将cookie数据合并到购物车
        pl = redis_conn.pipeline()
        pl.hmset('cart_%s' % user.id, cart)

        pl.sadd('cart_selected_%s' % user, *selected_sku_id_list)
        pl.execute()

        # 清楚cookie中的购物车数据
        response.delete_cookie('cart')

        return response
    else:
        return response






